package cn.jy.controller;

import cn.jy.bean.Msg;
import cn.jy.pojo.Administrators;
import cn.jy.pojo.Apk;
import cn.jy.service.AdminService;
import cn.jy.service.ApkService;
import cn.jy.service.AppService;
import cn.jy.util.UploadFileUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class ApkController {
    @Autowired
    private  ApkService apkService;

    @Autowired
    private AdminService adminService;


    @ResponseBody
    @GetMapping("/Apk")
    public Msg books(@RequestParam(value = "pageNum",defaultValue = "1") int pn){
        if (pn<1){
            pn=1;
        }
        PageHelper.startPage(pn,5);
        List<Apk> apks = apkService.APK_LIST();
        PageInfo<Apk> apkPageInfo = new PageInfo<Apk>(apks, 100);
        /* PageInfo<administrators> booksPageInfo = new PageInfo<administrators>(administrators, 100);*/
        //将分页信息传入自定义类的返回值（returnData）
        return Msg.success().add("books",apkPageInfo);
    }


    @RequestMapping("/ap")
    public String a(Model model){
        List<Apk> apks = apkService.APK_LIST();
        model.addAttribute("msg",apks);
        return "ap";
    }

    @ResponseBody
    @PostMapping("/user")
    public Msg addUser( Apk apk, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(apk);
        //判断上传文件不为空
        if(!file.isEmpty()){
            //可以获取服务器的地址  request.getServletContext().getRealPath
            //文件上床要保存的路径
            String realPath = request.getServletContext().getRealPath("/upload");

            //获取上传文件的名字
            String filename = file.getOriginalFilename();

            //判断文件的类型和大小
            if (!UploadFileUtils.isImageFile(filename)){
                return Msg.fail().add("info","文件类型不匹配");
            }
            //给上传的文件重命名
            filename=UploadFileUtils.imgReName(filename);
            System.out.println(filename);
            // 创建文件实例
            File filePath = new File(realPath, filename);
            //判断目录是否存在 不存在则创建
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
                System.out.println("创建目录" + filePath);
            }
            //给user对象的pic属性 赋值
/*
            user.setPic("upload/"+filename);
            //写入文件 将上传的文件复制到目录
            file.transferTo(filePath);
            //添加对象
*/


        }
/*        int i = userService.addUser(user);
        if(i>0){
            return Msg.success().add("info","用户添加成功");
        }*/




        return Msg.success();
    }
}

